<template>
  <div class="health-check-form">
    <div class="form-container">
      <h2>从业人员健康体检企业申报</h2>

      <el-form class="form-con" ref="formRef" :model="form" label-width="120px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="企业名称" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入企业"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="机构代码" prop="socialCreditCode" label-width="160px">
              <el-input v-model="form.socialCreditCode" placeholder="机构代码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="所属地区" prop="parkId">
              <el-select v-model="form.parkId" filterable placeholder="请选择">
                <el-option
                    v-for="item in parks"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--按钮-->
        <el-row>
          <el-col :span="1.5" style="margin-left: 35px;margin-top: 20px;">
            <el-button
                type="info"
                plain
                icon="Plus"
                @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <!-- TODO 批量导入功能待完善 -->
          <!--          <el-col :span="1.5" style="margin-left: 20px;margin-top: 20px;">-->
          <!--            <el-button-->
          <!--                type="primary"-->
          <!--                plain-->
          <!--                icon="Upload"-->
          <!--                @click="handleImport"-->
          <!--            >批量导入-->
          <!--            </el-button>-->
          <!--          </el-col>-->

        </el-row>
        <!--添加表格-->
        <el-table :data="applyTableData" border height="250" style="width: 95%;margin: 10px 35px;">
          <el-table-column align="center" prop="name" label="姓名"/>
          <el-table-column align="center" prop="idCard" label="身份证" width="150" show-overflow-tooltip="true"/>
          <el-table-column align="center" width="60" prop="age" label="年龄"/>
          <el-table-column label="性别" align="center" prop="gender">
            <template #default="scope">
              {{ scope.row.gender === 1 ? '男' : scope.row.gender === 0 ? '女' : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" width="60" prop="ethnic" label="民族"/>
          <el-table-column align="center" prop="educationLevel" label="文化程度"/>
          <el-table-column align="center" width="60" prop="workYears" label="工龄"/>
          <el-table-column align="center" prop="parkId" label="所属地区" width="100">
            <template #default="scope">
              <span>{{ getJobTypeLabel(scope.row.parkId, parks) }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="phone" label="联系电话" width="120"/>
          <el-table-column align="center" prop="jobTypeId" label="工种" width="100" show-overflow-tooltip="true">
            <template #default="scope">
              <span>{{ getJobTypeLabel(scope.row.jobTypeId, jobTypes) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="address" label="家庭地址" width="150" show-overflow-tooltip="true"/>
          <el-table-column align="center" prop="unitName" label="企业名称" width="120" show-overflow-tooltip="true"/>
          <el-table-column align="center" prop="socialCreditCode" label="机构代码" width="120"
                           show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <!--          <el-table-column prop="remark" label="备注"/>-->
        </el-table>

        <div class="legal-notice">
          <p>企业信用承诺书</p>
          <p>
            根据《中华人民共和国传染病防治法》、《中华人民共和国食品安全法》、《中华人民共和国药品管理法》、《公共场所卫生管理条例》、《化妆品卫生监督条例》、《生活饮用水卫生监督管理办法》等法律法规规定，本人需进行从业人员健康体检，我对本人身份及岗位的真实性作出承诺，并承担相应的法律责任。</p>

          <el-checkbox v-model="form.agreeTerms">请阅读以上条款并勾选</el-checkbox>
        </div>

        <div class="form-actions">
          <el-button size="large" type="danger" @click="submitForm">提交</el-button>
          <el-button size="large" @click="goBack">返回</el-button>
        </div>
      </el-form>

      <!-- 添加人员信息对话框 -->
      <el-dialog title="新增人员信息" v-model="addFormOpen" width="666px" append-to-body>
        <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="100px" label-position="top"
                 style="padding: 5px 80px;">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="身份证" prop="idCard">
            <el-input v-model="addForm.idCard" placeholder="请输入身份证号码" @input="handleIdCardInput"/>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="addForm.age" placeholder="请输入年龄"/>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="addForm.gender" placeholder="请选择">
              <el-option label="男" :value=1></el-option>
              <el-option label="女" :value=0></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="ethnic">
            <el-select v-model="addForm.ethnic" filterable placeholder="请选择">
              <el-option
                  v-for="item in ethnics"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文化程度" prop="educationLevel">
            <el-select v-model="addForm.educationLevel" placeholder="请选择">
              <el-option label="小学" value="小学"></el-option>
              <el-option label="初中" value="初中"></el-option>
              <el-option label="高中" value="高中"></el-option>
              <el-option label="大专" value="大专"></el-option>
              <el-option label="本科" value="本科"></el-option>
              <el-option label="硕士" value="硕士"></el-option>
              <el-option label="博士" value="博士"></el-option>
              <el-option label="教授" value="教授"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工龄" prop="workYears">
            <el-input v-model="addForm.workYears" placeholder="请输入工龄"/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="addForm.phone" placeholder="请输入联系电话"/>
          </el-form-item>
          <el-form-item label="工种" prop="jobTypeId">
            <el-select-v2
                v-model="addForm.jobTypeId"
                :options="jobTypes"
                filterable
                placeholder="请选择工种"
            />
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="addForm.address" placeholder="请输入家庭地址"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="addDataToTable">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 修改人员信息对话框 -->
      <el-dialog title="修改人员信息" v-model="editFormOpen" width="666px" append-to-body>
        <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" label-position="top"
                 style="padding: 5px 80px;">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="身份证" prop="idCard">
            <el-input v-model="editForm.idCard" placeholder="请输入身份证号码" @input="handleIdCardInput"/>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="editForm.age" placeholder="请输入年龄"/>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="editForm.gender" placeholder="请选择">
              <el-option label="男" :value=1></el-option>
              <el-option label="女" :value=0></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="民族" prop="ethnic">
            <el-select v-model="editForm.ethnic" filterable placeholder="请选择">
              <el-option
                  v-for="item in ethnics"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文化程度" prop="educationLevel">
            <el-select v-model="editForm.educationLevel" placeholder="请选择">
              <el-option label="小学" value="小学"></el-option>
              <el-option label="初中" value="初中"></el-option>
              <el-option label="高中" value="高中"></el-option>
              <el-option label="大专" value="大专"></el-option>
              <el-option label="本科" value="本科"></el-option>
              <el-option label="硕士" value="硕士"></el-option>
              <el-option label="博士" value="博士"></el-option>
              <el-option label="教授" value="教授"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工龄" prop="workYears">
            <el-input v-model="editForm.workYears" placeholder="请输入工龄"/>
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="editForm.phone" placeholder="请输入联系电话"/>
          </el-form-item>
          <el-form-item label="工种" prop="jobTypeId">
            <el-select v-model="editForm.jobTypeId" filterable placeholder="请选择">
              <el-option
                  v-for="item in jobTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="家庭住址" prop="address">
            <el-input v-model="editForm.address" placeholder="请输入家庭地址"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="editDataToTable">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 批量导入弹框 -->
      <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                   :action="upload.url" :disabled="upload.isUploading"
                   :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
                       @click="importTemplate">下载模板
              </el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  ethnics,
  jobTypes,
  loadEthnic,
  loadJobTypes,
  loadParkId,
  openNotice,
  parks,
  rules
} from "@/api/employee/applyBaseData.js";
// 引入调用request方法
import {addUnitApply} from "@/api/employee/unitApply.js";
import {debounce} from "lodash-es";

const {proxy} = getCurrentInstance()

const formRef = ref(null)
const addFormRef = ref(null)
const editFormRef = ref(null)
const addFormOpen = ref(false) //定义添加的模态框
const editFormOpen = ref(false) //定义修改的模态框
const title = ref("") // 定义模态框标题

// 定义单位最外层表单值
const form = ref({
  unitName: '',
  socialCreditCode: '',
  parkId: null,
  isUnit: 1,
  agreeTerms: false
})

// 单位新增表单值
const addForm = ref({
  name: '',
  idCard: '',
  age: null,
  gender: null,
  ethnic: '',
  educationLevel: '',
  workYears: null,
  phone: '',
  jobTypeId: null,
  address: '',
})

// 单位编辑表单值
const editForm = ref({
  name: '',
  idCard: '',
  age: null,
  gender: null,
  ethnic: '',
  educationLevel: '',
  workYears: null,
  phone: '',
  jobTypeId: null,
  address: '',
})

// 单位表格数据
const applyTableData = reactive(
    [
      /*{
        id: 1,
        name: '张三',
        idCard: '350123199506164477',
        age: 29,
        gender: 1,
        ethnic: '汉族',
        educationLevel: '本科',
        workYears: 5,
        parkId: 101,
        phone: '13812345678',
        jobTypeId: 1,
        address: '北京市海淀区',
        unitName: '巴拉巴拉部门',
        socialCreditCode: '4234321234567',
        isUnit: 1
      }, {
      id: 2,
      name: '李四',
      idCard: '140427199307248902',
      age: 31,
      gender: 0,
      ethnic: '汉族',
      educationLevel: '本科',
      workYears: 5,
      parkId: 102,
      phone: '15162345678',
      jobTypeId: 2,
      address: '北京市海淀区',
      unitName: '咕噜咕噜部门',
      socialCreditCode: '4123423412213',
      isUnit: 1
    },*/
    ]
)
/** 单位批量导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  // headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/employee/unitApply/importData"
})

/** 单位导入按钮操作 */
function handleImport() {
  upload.title = "企业申报批量导入"
  upload.open = true
}

/** 单位批量新增操作 */
function handleBatchAdd() {
  // todo
}

/** 单位下载模板操作 */
function importTemplate() {
  proxy.download("/employee/unitApply/importTemplate", {}, `unitBatchAdd_template_${new Date().getTime()}.xlsx`)
}

/** 单位提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

/**单位文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 单位文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true})
  getList()
}

/** 单位新增按钮操作 */
function handleAdd() {
  formRef.value.validate(valid => {
    if (valid) {
      addFormOpen.value = true
      resetForm('add');
    } else {
      ElMessage.error('请先填写单位和园区信息！');
      return false;
    }
  })
}

// 单位取消按钮
function cancel() {
  addFormOpen.value = false
  editFormOpen.value = false
}

// 单位把表单的数据添加到表格中
function addDataToTable() {
  // 检查单位表单是否有效
  addFormRef.value.validate(valid => {
    if (valid) {
      // 将单位表单数据复制到新对象
      const newData = {
        id: applyTableData.length + 1,
        ...addForm.value,
        parkId: form.value.parkId,
        isUnit: form.value.isUnit,
        unitName: form.value.unitName,
        socialCreditCode: form.value.socialCreditCode
      };
      // 如果需要，可以重置表单字段
      applyTableData.push(newData);
      resetForm();
      addFormRef.value.resetFields(); // 清除所有校验提示
      addFormOpen.value = false
      ElMessage.success("新增成功");
    } else {
      ElMessage.error('请填写完整信息!');
      return false;
    }
  });
}

// 把单位表单的数据进行修改
function editDataToTable() {
  editFormRef.value.validate(valid => {
    if (valid) {
      // 找到需要修改的索引
      const index = applyTableData.findIndex(item => item.id === editForm.value.id);
      if (index !== -1) {
        // 更新单位表格中的数据（保留 id）
        applyTableData[index] = {
          ...applyTableData[index],
          ...editForm.value,

          // 外层表单的园区/单位等不变
          // parkId: form.value.parkId,
          // unitName: form.value.unitName,
          // socialCreditCode: form.value.socialCreditCode,
          // isUnit: form.value.isUnit
        };
      }

      ElMessage.success("修改成功");
      editFormOpen.value = false;
    } else {
      ElMessage.error('请填写完整信息!');
      return false;
    }
  });
}

/** 通过表格id获取表格数据 */
function getAllDataById(id) {
  return applyTableData.filter(item => item.id === id)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  //  通过id获取表格数据
  const id = row.id || ids.value
  getAllDataById(id).forEach(item => {
    editForm.value = item
  })
  editFormOpen.value = true
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
      '确定要删除该人员信息吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const index = applyTableData.findIndex(item => item.id === row.id);
    if (index !== -1) {
      applyTableData.splice(index, 1); // 删除表格中的对应行
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("未找到要删除的数据");
    }
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
}

/** 清空表格数据 */
function clearApplyTableData() {
  applyTableData.splice(0, applyTableData.length); // 清空表格数据
}

// 后台id转为中文展示方法
function getJobTypeLabel(id, list) {
  let lableName = list.find(item => item.value == id);
  return lableName ? lableName.label : '未知';
}

// 重置添加/修改表单
function resetForm(value) {
  if (value === 'add') {
    for (let key in addForm.value) {
      addForm.value[key] = ''
    }
    // addForm.value.id = null;
    addForm.value.age = null;
    addForm.value.gender = null;
    addForm.value.workYears = null;
    addForm.value.jobTypeId = null;
  } else if (value === 'edit') {
    for (let key in editForm.value) {
      editForm.value[key] = ''
    }
    editForm.value.age = null;
    editForm.value.gender = null;
    editForm.value.workYears = null;
    editForm.value.jobTypeId = null;
  }
}

/** 最终传入后端的数据组装 使用compute=>这样无论什么时候访问 submitData.value，都能得到当前最新的表单数据。*/
const submitData = computed(() => ({
  unitName: form.value.unitName,
  socialCreditCode: form.value.socialCreditCode,
  parkId: form.value.parkId,
  unitPersonList: [...applyTableData],
  isUnit: form.value.isUnit
}));

// 防止重复提交
const submitForm = debounce(rawSubmitForm, 600)
/*提交表单数据*/
function rawSubmitForm () {
  formRef.value.validate(valid => {
    if (valid && form.value.agreeTerms) {
      // 注意数据提交格式,所以得使用submitData来提交
      console.log(submitData.value)
      addUnitApply(submitData.value).then(response => {
        if (response.code === 200) {
          ElMessage.success("新增成功")
          clearApplyTableData() // 清空表格数据
          formRef.value.resetFields() // 清除所有校验提示
        } else {
          ElMessage.error('新增失败:' + response.msg)
        }
      })
    } else if (!valid) {
      return false
    } else if (!form.value.agreeTerms) {
      ElMessage.error('请阅读并同意条款!')
      return false
    }
  })
}

const goBack = () => {
  // 这里可以根据实际路由配置进行调整
  window.history.back()
}

// 验证身份证格式是否正确（简单验证）
function validIdCard(idCard) {
  return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCard)
}

function handleIdCardInput(value) {
  // 将输入的字母 x 转换为大写
  addForm.value.idCard = value.replace(/x/g, 'X');
  editForm.value.idCard = value.replace(/x/g, 'X');
}

// 监听身份证的变化
watch(() => addForm.value.idCard, (newVal) => {
  if (validIdCard(newVal)) {
    const birthYear = parseInt(newVal.substring(6, 10))
    const currentYear = new Date().getFullYear()
    const genderDigit = parseInt(newVal.charAt(16)) // 第17位（从0开始计数）
    // 设置年龄
    addForm.value.age = currentYear - birthYear
    // 设置性别（1 为男，0 为女）
    addForm.value.gender = genderDigit % 2 === 1 ? 1 : 0
  }
})

// 资源加载就执行的方法
onMounted(() => {
  // 这里执行需要DOM加载完成后才能执行的操作
  openNotice();//通知
  loadEthnic();
  loadParkId();
  loadJobTypes();
})

</script>

<style scoped>
.health-check-form {
  background-color: #f5f5f5;
  background-image: url('');
  min-height: 100vh;
  padding: 20px;
}

.form-container {
  background-color: white;
  padding: 30px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 1400px;
  margin: 0 auto;
}

h2 {
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.upload-section {
  margin: 30px 0;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.upload-tips {
  color: #909399;
  font-size: 14px;
  margin: 5px 0;
}

.legal-notice {
  margin: 30px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.legal-notice p {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.el-button + .el-button {
  margin-left: 20px;
}

.form-con {
  margin-top: 45px;
}

</style>